/**
 * Copyright phonemap.com
 *
 * Licensed under the phonemap.com License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.phonemap.com/licenses/LICENSE-1.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Constructor.
 * @param page {String}
 */
function PhonemapLocation(page) {
	
}

/**
 * Do geolocation.
 */
function doGeolocation() {
	if (navigator.geolocation) {
		navigator.geolocation
				.getCurrentPosition(positionSuccess, positionError);
	} else {
		positionError(-1);
	}
}

/**
 * Position error.
 * @param err
 */
function positionError(err) {
	//var msg;
	switch (err.code) {
		case err.UNKNOWN_ERROR:
			msg = "Unable to find your location";
			break;
		case err.PERMISSION_DENINED:
			msg = "Permission denied in finding your location";
			break;
		case err.POSITION_UNAVAILABLE:
			msg = "Your location is currently unknown";
			break;
		case err.BREAK:
			msg = "Attempt to find location took too long";
			break;
		default:
			msg = "You need to enable location on browser to continue...";
	}
	document.getElementById('status').innerHTML = msg;
}

/**
 * Position Success.
 * @param position
 */
function positionSuccess(position) {
	// Centre the map on the new location
	var coords = position.coords || position.coordinate || position;
	var latLng = new google.maps.LatLng(coords.latitude, coords.longitude);
	curpos = latLng;

	// And reverse geocode.
	(new google.maps.Geocoder()).geocode({
		latLng : latLng
	}, function(resp) {
		if (resp[0]) {
			var bits = [];
			for (var i = 0, I = resp[0].address_components.length; i < I; ++i) {
				var component = resp[0].address_components[i];
				if (contains(component.types, 'political')) {
					bits.push('<b>' + component.long_name + '</b>');
				}
			}
			if (bits.length) {
				place = bits.join(' > ');
			}
			address = resp[0].formatted_address
		}
	});
	
	insertFacebookUser();
}

/**
 * Contains.
 * @param array
 * @param item
 * @returns {Boolean}
 */
function contains(array, item) {
	for (var i = 0, I = array.length; i < I; ++i) {
		if (array[i] == item)
			return true;
	}
	return false;
}